<?php

/*
 * Fresns (https://fresns.org)
 * Copyright (C) 2021-Present Jevan Tang
 * Released under the Apache-2.0 License.
 */

namespace Plugins\SsoApi\Http\Controllers;

use App\Exceptions\ApiException;
use App\Fresns\Api\Services\AccountService;
use App\Fresns\Api\Services\UserService;
use App\Fresns\Api\Traits\ApiResponseTrait;
use App\Helpers\ConfigHelper;
use App\Helpers\PrimaryHelper;
use Illuminate\Routing\Controller;

class ApiController extends Controller
{
    use ApiResponseTrait;

    public function detail()
    {
        $aid = \request()->header('X-Fresns-Aid');
        $uid = \request()->header('X-Fresns-Uid');

        // account
        $account = PrimaryHelper::fresnsModelByFsid('account', $aid);
        if (empty($account)) {
            throw new ApiException(31502);
        }
        if ($account->is_enabled == 0) {
            throw new ApiException(34307);
        }

        // user
        $user = PrimaryHelper::fresnsModelByFsid('user', $uid);
        if (empty($user)) {
            throw new ApiException(31602);
        }
        if ($user->is_enabled == 0) {
            throw new ApiException(35202);
        }

        // lang and timezone
        $defaultLanguage = ConfigHelper::fresnsConfigDefaultLangTag();
        $langTag = \request()->header('X-Fresns-Client-Lang-Tag', $defaultLanguage);

        $defaultTimezone = ConfigHelper::fresnsConfigDefaultTimezone();
        $timezone = \request()->header('X-Fresns-Client-Timezone', $user?->timezone) ?? $defaultTimezone;

        // id
        $data['primaryId'] = [
            'accountId' => $account->id,
            'userId' => $user->id,
        ];

        // detail
        $accountService = new AccountService();
        $data['accountDetail'] = $accountService->accountDetail($account, $langTag, $timezone);

        $userService = new UserService();
        $data['userDetail'] = $userService->userData($user, $langTag, $timezone);

        return $this->success($data);
    }
}
